import fetch from 'fermionjs/lib/fetch';
import pkg from '../../../package.json';
const { name } = pkg;

// TODO 单次发送短信数量建议不超过200
export default function sendSMSBatch({ to, templateId, content }) {
	const {
		log,
		app: {
			config: {
				[name]: { yunpianTplBatchApi, yunpianApiKey },
			},
		},
	} = this;
	to = Array.from(new Set(to));
	if (!to.length) return;
	if (to.length > 200) {
		const data = dealBatchSend({ to, templateId, content });
		return Promise.all(
			data.map(item => {
				fetchSMS(log, yunpianApiKey, yunpianTplBatchApi, item);
			})
		);
	} else {
		return fetchSMS(log, yunpianApiKey, yunpianTplBatchApi, {
			to,
			templateId,
			content,
		});
	}
}
function dealBatchSend(data) {
	const { to } = data;
	const dataObj = Object.assign({}, data);
	const len = to.length;
	const dataArr = [];
	const page = Math.ceil(len / 200);
	for (let i = 0; i < page; i++) {
		dataObj.to = to.slice(i * 200, (i + 1) * 200);
		dataArr.push(dataObj);
	}
	return dataArr;
}

function fetchSMS(
	log,
	yunpianApiKey,
	yunpianTplBatchApi,
	{ to, templateId, content }
) {
	const len = to.length;
	to = to.join();
	const body = new URLSearchParams({
		mobile: to,
		apikey: yunpianApiKey,
		tpl_id: templateId,
		tpl_value: new URLSearchParams(content),
	}).toString();
	log.debug({ to, body }, '发送短信');

	return fetch(yunpianTplBatchApi, {
		body,
		method: 'POST',
		headers: {
			Accept: 'application/json;charset=utf-8',
			'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
		},
	})
		.then(response => {
			if (!response.total_count) {
				log.error({ response }, '短信发送：短信发送失败');
				throw new Error('短信发送失败');
			} else if (response.total_count && response.total_count !== len) {
				log.info(response, '部分告警人接收短信失败');
			}
			return response;
		})
		.catch(err => {
			log.error({ err }, '短信发送：短信发送失败');
			throw new Error('短信发送失败--catch');
		});
}
